package stream.menu;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 真香
 * @create 2021-11-10 23:01
 */
public class MenuTree {


    @Test
    public void testTree() {

        List<Menu> menus = Arrays.asList(
            new Menu(1, "根节点", 0),
            new Menu(2, "子节点1", 1),
            new Menu(3, "子节点1,1", 2),
            new Menu(4, "子节点1.2", 2),
            new Menu(5, "子节点1.3", 2),
            new Menu(6, "根节点2", 1),
            new Menu(7, "根节点2.1", 6),
            new Menu(8, "根节点2.2", 6),
            new Menu(9, "根节点2.2.1", 7),
            new Menu(10, "根节点2.2.2", 7),
            new Menu(11, "根节点3", 1),
            new Menu(12, "根节点3.1", 11)
        );


        // 获取父节点
        List<Object> collect = menus.stream().filter(menu -> menu.getParentId() == 0).map(
                (menu -> {
                    menu.setChildList(getChildrens(menu, menus));
                    return menu;
                })
        ).collect(Collectors.toList());
        System.out.println("-------转json输出结果-------");
        System.out.println(JSON.toJSON(collect));

    }


    /**
     *  递归查询子节点
     * @param root  根节点
     * @param all   所有节点
     * @return 根节点信息
     */
    private List<Menu> getChildrens (Menu root,List<Menu> all){

        List<Menu> children = all.stream().filter(menu -> {
            return Objects.equals(menu.getParentId(), root.getId());
        }).map(
                menu -> {
                    menu.setChildList(getChildrens(menu, all));
                    return menu;
                }
        ).collect(Collectors.toList());
        return children;
    }

    @Test
    public void test2(){

        Map<String,String> params =new HashMap<>();

        params.put("keyworld","搜索,古驰,LV,森马");

        if (StringUtils.isNotEmpty(params.get("keyworld"))){
            List<String> keyworlds = Arrays.asList(params.get("keyworld").split(",")).stream().collect(Collectors.toList());
            Collections.shuffle(keyworlds);
            params.put("keyworld",keyworlds.get(0));
            System.out.println(JSON.toJSON(params));
        }

    }

}



